﻿using Model.DocumentDB;
using Model.DocumentDB.Manifest;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Studio.DocumentDB
{
    /// <summary>Main Window of the Studio.</summary>
    /// <remarks>
    /// Get started:  http://azure.microsoft.com/en-us/documentation/articles/documentdb-get-started
    /// </remarks>
    public partial class MainWindow : Window
    {
        private readonly StudioViewModel _viewModel = new StudioViewModel();

        /// <summary>Constructor.</summary>
        public MainWindow()
        {
            InitializeComponent();

            DataContext = _viewModel;
        }

        protected async override void OnInitialized(EventArgs e)
        {
            var snapshotApiUrl = ConfigurationManager.AppSettings["snapshotApiUrl"];
            var releaseVersion = GetType().Assembly.GetName().Version;

            base.OnInitialized(e);

            version.Content = releaseVersion;

            TelemetryAgent.Instance.Start(snapshotApiUrl);

            await LoadAccountsAsync();
            await CheckManifestAsync(releaseVersion);
        }

        protected async override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            await TelemetryAgent.Instance.StopAsync();
        }

        private async Task<int?> LoadAccountsAsync()
        {
            await ErrorHelper.HandleAsync(
                () => _viewModel.Accounts.EnsureLoadedAsync(),
                this,
                "Studio file is corrupted:  can't read accounts." + Environment.NewLine + "{0}");

            return _viewModel.Accounts.HasError ? (int?)null : _viewModel.Accounts.Count();
        }

        private async Task<int?> CheckManifestAsync(Version releaseVersion)
        {
            var manifest = await XmlManifest.LoadAsync();

            if (manifest != null)
            {
                var newerReleases = manifest.GetNewerReleases(releaseVersion);

                if (newerReleases.Any())
                {
                    var message = string.Format(
                        "You are running version {0} while version {1} is available at {2}",
                        releaseVersion,
                        newerReleases.Last().Version,
                        manifest.DownloadUri);

                    MessageBox.Show(this, message, "New Release available", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                }

                return newerReleases.Length;
            }
            else
            {
                return null;
            }
        }
    }
}
